﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using Argos.Activities.MessageDelivery;

namespace ArgosDesktop
{
	public partial class Alerts : Form
	{

		public Alerts()
		{
			InitializeComponent();

			this.Size = Settings.Default.FormSize;
		}



		public void RefreshAlerts()
		{
			this.ReloadAlerts();
		}



		protected override void OnClosing(CancelEventArgs e)
		{
			base.OnClosing(e);
			if (!e.Cancel && this.WindowState == FormWindowState.Normal)
			{
				Settings.Default.FormSize = this.Size;
				Settings.Default.Save();

				this.DialogResult = DialogResult.OK;
			}
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			this.autoRefreshToolStripMenuItem.Checked = Settings.Default.AutoRefresh;

			this.ReloadAlerts();
		}



		private void ReloadAlerts()
		{
			this.AlertViewer.Items.Clear();
			List<string> alerts = new List<string>(Directory.GetFiles(UserSettings.Default.AlertStorageFolder, "*.xml").OrderBy(s => s).Reverse());

			foreach (string s in alerts)
			{
				this.AlertViewer.Items.Add(AlertMessage.ReadXml(new FileInfo(s)));
			}
		}

		private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.ReloadAlerts();
		}

		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void autoRefreshToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.autoRefreshToolStripMenuItem.Checked = !this.autoRefreshToolStripMenuItem.Checked;

			Settings.Default.AutoRefresh = this.autoRefreshToolStripMenuItem.Checked;
			Settings.Default.Save();
		}

		private void autoRefreshToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
		{
			if (autoRefreshToolStripMenuItem.Checked)
			{
				this.AlertsWatcher.Path = UserSettings.Default.AlertStorageFolder;
				this.AlertsWatcher.EnableRaisingEvents = true;
			}
			else
			{
				this.AlertsWatcher.EnableRaisingEvents = false;
			}
		}

		private void AlertsWatcher_Changed(object sender, FileSystemEventArgs e)
		{
			if (Settings.Default.AutoRefresh)
				this.ReloadAlerts();
		}



		private class Settings : ApplicationSettingsBase
		{

			public static Settings Default = (Settings)ApplicationSettingsBase.Synchronized(new Settings());


			[UserScopedSetting]
			[DefaultSettingValue("False")]
			public bool AutoRefresh
			{
				get { return (bool)this["AutoRefresh"]; }
				set { this["AutoRefresh"] = value; }
			}

			[UserScopedSetting]
			[DefaultSettingValue("400,300")]
			public Size FormSize
			{
				get { return (Size)this["FormSize"]; }
				set { this["FormSize"] = value; }
			}

		}

	}
}
